<!-- 照片裁剪 -->
<template>
  <el-dialog
    v-model="display"
    title="裁剪图片"
    width="80%"
    :append-to-body="true"
  >
    <div>
      <vue-picture-cropper
        :boxStyle="{
          width: '100%',
          height: '100%',
          maxHeight: '60vh',
          backgroundColor: '#f8f8f8',
          margin: 'auto',
        }"
        :img="pic"
        :options="options"
        :key="numKey"
      />
    </div>
    <div class="flex c1">
      <el-button
        @click="
          options.aspectRatio = 500 / 281;
          numKey++;
        "
        >500:281</el-button
      >
      <el-button
        @click="
          options.aspectRatio = 1 / 1;
          numKey++;
        "
        >1:1</el-button
      >
      <el-button @click="clearCropper">不裁剪</el-button>
      <el-button @click="display = false">关闭</el-button>
      <el-button type="primary" @click="successImg()">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import VuePictureCropper, { cropper } from "vue-picture-cropper";
import { ElMessage } from "element-plus";

const emit = defineEmits<{
  (e: "update:show", data: boolean): void; //向父组件更新 弹窗是否显示
  (e: "img", data?: string): void; //向父组件传递 图片裁剪成功的数据
}>();

const props = defineProps({
  //是否显示弹窗
  show: {
    type: Boolean,
    default: false,
  },
  //需要上传的空间名称
  name: {
    type: String,
    default: "",
  },
  //需要裁剪的图片
  pic: {
    type: String,
    default: "",
  },
});

const numKey = ref(1);

function clearCropper() {
  cropper!.clear();
}

const options = ref({
  viewMode: 1,
  dragMode: "crop",
  aspectRatio: 1 / 1,
});

const display = ref(false);

watch(
  props,
  (newVal, oldVal) => {
    display.value = newVal.show;
  },
  { immediate: true }
);

watch(
  display,
  (newVal, oldVal) => {
    emit("update:show", newVal);
  },
  { immediate: true }
);

//确定图片 获取裁切结果
function successImg() {
  let base64 = cropper!.getDataURL({
    fillColor: "transparent",
  });

  console.log(base64);

  //预览后台，操作提示
  ElMessage.success("裁剪获取base64数据成功，这里需要对接图片上传后台功能");

  let url = "other/verify2.jpg"; //上传成功之后返回的图片url路径

  emit("img", url); //返回上传成功之后的图片url路径
  emit("update:show", false);
}
</script>

<style scoped lang="scss">
.c1 {
  justify-content: flex-end;
  margin-top: 10px;
}

.c1 .a-but {
  margin-left: 20px;
}
</style>
